package cn.edu.zjgsu.controller;

import cn.edu.zjgsu.dao.PermissionDao;
import cn.edu.zjgsu.dao.UserDao;
import cn.edu.zjgsu.model.Permission;
import cn.edu.zjgsu.model.User;
import cn.edu.zjgsu.template.ResultBean;
import cn.edu.zjgsu.vo.LoginInput;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author: mwq
 * DateTime: 2017/11/7 22:14
 * Description:
 */
@RestController
@Slf4j
public class LoginController
{

    @Autowired
    UserDao userDao;
    @Autowired
    PermissionDao permissionDao;

    @GetMapping(path = "/hello")
    public String helloWorld()
    {
        return "Hello World! 你好";
    }

    /**
     * 登录
     * @param loginInput
     * @return
     */
    @PostMapping(path = "login")
    public ResultBean login(@RequestBody LoginInput loginInput)
    {
        ResultBean result = new ResultBean();
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(loginInput.getUsername(),loginInput.getPassword());
        try
        {
            subject.login(token);
        } catch (UnknownAccountException e)
        {
            result.setMsg("用户名不存在");
            result.setCode(400);
            return result;
        } catch (IncorrectCredentialsException e)
        {
            result.setMsg("密码错误");
            result.setCode(400);
            return result;
        }

        result.setCode(200);
        return result;
    }

    /**
     * 登出
     * @return
     */
    @GetMapping(path = "logout")
    public ResultBean logout()
    {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return new ResultBean();
    }


    @GetMapping(path = "testPermission")
    public String testPermission(@RequestParam String username)
    {
        StringBuffer sb = new StringBuffer();
        List<Permission> permissionList = permissionDao.findByHQL
                ("select p from Role r,Permission p where r.username = ? and p.roleName=r.roleName", username);
        for (int i = 0,length=permissionList.size(); i <length ; i++)
        {
            sb.append(permissionList.get(i).getPermissionName());
        }
        return sb.toString();
    }

}
